#!/usr/bin/perl -w
#   Written by Jimmy Saw - 08-24-2008
#   This program takes a Genbank file and converts it into ptt file
#   You have to redirect output to a file
#   perl parse-gb2ptt.pl x.gbk > y.ptt

use Bio::SeqIO;

my $seqio_obj = Bio::SeqIO->new( -file => $ARGV[0], -format => 'genbank' );
my $seq_obj   = $seqio_obj->next_seq;

my $organism = $seq_obj->desc;

my $length = $seq_obj->length;

my $cdcount = 0;

for my $feat_obj ( $seq_obj->get_SeqFeatures ) {
	if ( $feat_obj->primary_tag eq "CDS" ) {
		if ( $feat_obj->has_tag('locus_tag') ) {
			$cdcount++;
		}
	}
}

print $organism, " - 1..", $length, "\n";
print $cdcount, " proteins", "\n";

print "Location", "\t", "Strand", "\t", "Length", "\t", "PID", "\t", "Gene",
	"\t", "Synonym", "\t", "Code", "\t", "COG", "\t", "Product", "\n";

for my $feat_obj ( $seq_obj->get_SeqFeatures ) {
	if ( $feat_obj->primary_tag eq "CDS" ) {
		if ( $feat_obj->has_tag('locus_tag') ) {
			for my $value ( $feat_obj->get_tag_values('locus_tag') ) {
				my $start = $feat_obj->start;
				my $end   = $feat_obj->end;
                my $cog = "";
                if($feat_obj->has_tag('note')){
                    #print $feat_obj->get_tag_values('note');
                    if ($feat_obj->get_tag_values('note') =~ /COGs: (\w+) .*/){
                        $cog = $1;
                    }
                    else{
                        $cog = "-";
                    }
                }
				if ( $feat_obj->strand == 1 ) {
                    if($feat_obj->has_tag('protein_id')){
					    print $start, "..", $end, "\t", "+", "\t",
						    ( ( $end - $start + 1 ) / 3 ) - 1, "\t",
						    $feat_obj->get_tag_values('protein_id'), "\t", "-", "\t", $value,
						    "\t", "-", "\t", $cog, "\t", $feat_obj->get_tag_values('product'),
						    "\n";
                    }
                    else{
					    print $start, "..", $end, "\t", "+", "\t",
						    ( ( $end - $start + 1 ) / 3 ) - 1, "\t",
						    "no PID", "\t", "-", "\t", $value,
						    "\t", "-", "\t", $cog, "\t", $feat_obj->get_tag_values('product'),
						    "\n";
                    }
				}
				else {
                    if($feat_obj->has_tag('protein_id')){
					    print $start, "..", $end, "\t", "-", "\t",
						    ( ( $end - $start + 1 ) / 3 ) - 1, "\t",
						    $feat_obj->get_tag_values('protein_id'), "\t", "-", "\t", $value,
						    "\t", "-", "\t", $cog, "\t", $feat_obj->get_tag_values('product'),
						    "\n";
                    }
                    else{
					    print $start, "..", $end, "\t", "-", "\t",
						    ( ( $end - $start + 1 ) / 3 ) - 1, "\t",
						    "no PID", "\t", "-", "\t", $value,
						    "\t", "-", "\t", $cog, "\t", $feat_obj->get_tag_values('product'),
						    "\n";
                    }
				}
			}
		}
	}
}
